<template>
	<div class="upload-wrap">
		<el-upload
			class="avatar-uploader"
			action="#"
			:http-request="UploadRequestHandler"
			:limit="100"
			:before-upload="beforeAvatarUpload"
			:on-success="handleAvatarSuccess"
			:on-exceed="handleExceed"
			:list-type="'picture'"
			multiple
			:on-change="handleChange"
			drag
		>
			<template #trigger>
				<el-button type="primary">select file</el-button>
			</template>

			<el-button class="ml-3" type="success" @click="submitHandler"> upload to server </el-button>

			<template #tip>
				<div class="el-upload__tip">jpg/png files with a size less than 500kb</div>
			</template>
		</el-upload>
	</div>
</template>

<script setup>
import instance from '@/utils/http'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

const imageUrl = ref('')
const form = reactive({
	file: null,
	filename: null
})

const handleAvatarSuccess = (response, uploadFile) => {
	// imageUrl.value = URL.createObjectURL(uploadFile.raw)
}
/**
 * 上传类型 / 大小 / 个数
 * @param {*} rawFile
 */
const beforeAvatarUpload = (rawFile) => {
	const typeArr = ['image/jpeg', 'image/jpg', 'image/png'] // 类型
	const uploadSize = rawFile.size / 1024 / 1024 > 2 // 大小
	if (!typeArr.includes(rawFile.type)) {
		ElMessage.error('Avatar picture must be JPG format!')
		return false
	} else if (uploadSize) {
		ElMessage.error('Avatar picture size can not exceed 2MB!')
		return false
	}
	return true
}
/**
 * 文件超出个数限制时的钩子
 */
const handleExceed = () => {
	ElMessage.error('超出最大上传限制')
}
const fileListData = ref([])
// 覆盖默认行为
const UploadRequestHandler = (params) => {
	console.log('%c [  ]-65', 'font-size:13px; background:pink; color:#bf2c9f;', params)
	imageUrl.value = URL.createObjectURL(params.file)
	form.file = params.file
	form.filename = params.file.name
}
const submitHandler = async () => {
	// fileListData.value = fileListData.value.map(item => {
	//   let fm = new FormData();

	//   fm.append('file', item.raw);
	//   fm.append('filename', item.filename);
	//   instance.post('/upload_single', fm, {
	//     // onUploadProgress(ev) {
	//     //   // 检测每一个的上传进度
	//     //   if (curSpan) {
	//     //     curSpan.innerHTML = `${(ev.loaded / ev.total * 100).toFixed(2)}%`;
	//     //   }
	//     // }
	//   }).then(data => {
	//     if (+data.code === 0) {
	//       // if (curSpan) {
	//       //   curSpan.innerHTML = `100%`;
	//       // }
	//       return;
	//     }
	//     return Promise.reject();
	//   });
	// });

	// // 等待所有处理的结果
	// Promise.all(fileListData.value).then(() => {
	//   alert('恭喜您，所有文件都上传成功~~');
	// }).catch(() => {
	//   alert('很遗憾，上传过程中出现问题，请您稍后再试~~');
	// }).finally(() => {

	// });
	// 多文件上传
	fileListData.value = fileListData.value.map(async (item) => {
		let formData = new FormData()
		formData.append('file', item.raw)
		formData.append('filename', item.raw.filename)
		try {
			const { code, codeText, servicePath } = await instance.post('/upload_single', formData)
			if (+code === 0) {
				// ElMessage.success(`文件已经上传成功~~,您可以基于 ${servicePath} 访问这个资源~~`)
				return
			}
			// return Promise.reject(codeText)
		} catch (error) {
			ElMessage.error(error)
		} finally {
			//  清除操作
		}
	})
	console.log('fileListData.value', fileListData.value)
	Promise.all(fileListData.value)
		.then(() => {
			ElMessage.success('恭喜您，所有文件都上传成功~~')
		})
		.catch(() => {
			ElMessage.error('很遗憾，上传过程中出现问题，请您稍后再试~~')
		})
		.finally(() => {})
	// 这样没法async await ？
	// try {
	//   const { code, codeText, servicePath } = await instance.post('/upload_single', formData)

	// for (let k = 0; k < fileListData.value.length; k++) {
	//   let item = fileListData.value[k]
	//   let formData = new FormData()
	//   formData.append('file', item.raw)
	//   formData.append('filename', item.raw.filename)
	// }

	// 这样没法async await ？
	// try {
	//   const { code, codeText, servicePath } = await instance.post('/upload_single', formData)
	//   if (+code === 0) {
	//     ElMessage.success(`文件已经上传成功~~,您可以基于 ${servicePath} 访问这个资源~~`)
	//     return
	//   }
	//   // return Promise.reject(codeText)
	// } catch (error) {
	//   ElMessage.error(error)
	// } finally {
	//   //  清除操作
	// }
	// }
}
// formData.append('file', form.file)
// formData.append('filename', form.filename)

const handleChange = (file, fileList) => {
	fileListData.value = fileList
	console.log('%c [  ]-94', 'font-size:13px; background:pink; color:#bf2c9f;', fileListData.value)
}
</script>

<style scoped lang="scss">
.upload-wrap {
	border: 1px solid blue;
	width: 50vh;
	height: 100%;
	padding: 10px;
}

.avatar-uploader .avatar {
	width: 178px;
	height: 178px;
	display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
	border: 1px dashed var(--el-border-color);
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
	border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	text-align: center;
}
</style>
